var express = require("express");
var mongodb = require("mongodb");
var url = require("url");
var ArticleProvider = require("./article-memory").ArticleProvider;
var serveIndex = require("./index").serveIndex;
var app = express.createServer();

app.configure(function() {
  app.set("views", __dirname + "/views");
  app.set("view engine", "jade");
  app.use(express.bodyParser());
});

var articleProvider = new ArticleProvider("localhost", 28017);
//articleProvider.bootstrap();

app.get("/", function(req, res) {
  articleProvider.findAll(function(error, docs) {
    res.render("index.jade", {locals:{title:"Show all posts", articles:docs}});
  });
});

app.get("/blog/new", function(req, res) {
    res.render("new_post.jade", { locals: {
        title: "New Post"
    }
    });
});

app.post("/blog/new", function(req, res){  
  articleProvider.save({title: req.param("title"), body: req.param("body")},
    function( error, docs) {
        res.redirect('/')
    });
});

app.get("/blog/:id", function(req, res) {
  articleProvider.findById(req.params.id, function(error, doc) {
    res.render("view_post.jade", {locals:{title:doc.title, article:doc}});
  });
});

app.listen(3000);
